﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class JF_FeeItemInterfaceBusiness : JFInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption JF_Query;
        public JF_FeeItemInterfaceBusiness()
        {
            this.InterfaceName = "JF费用明细";
            //索引字段
            this.MapFields = GetMapField("JF_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            JF_Query = this.interfaceOption.Where(x => x.OperateType == "JF_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="JF_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, JF_NoQueryEventArgs JF_NoQueryEventArgs)
        {
            //API请求是否成功
            JF_NoQueryEventArgs.Success = JF_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, JF_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取配置参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var parameters = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='JiuFang'");
                //设置请求头
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("appKey", parameters.Where(x => x.Name == "appKey").First().Value);
                headers.Add("appToken", parameters.Where(x => x.Name == "appToken").First().Value);
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                //查询的时间
                queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.TargetField == "feeTimeStart").First().Notes.ToInt();
                //设置单次查询的页面数量
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "limit").First().SourceField.ToInt();
                queryEventArgs.Page.PageIndex = 1;
                queryEventArgs.Page.Temp1 = 0;
                //获取费用类型
                var feeType = queryEventArgs.APINodes.Where(x => x.TargetField == "feeType").First().Notes.Split(",");
                queryEventArgs.CustomData = feeType;
                queryEventArgs.Page.Temp2 = feeType.Count();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, JF_QueryEventArgs queryEventArgs)
        {
            //json参数
            JF_ReqDTO data = new JF_ReqDTO();
            data.page = queryEventArgs.Page.PageIndex;
            data.date_from=DateTime.Now.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd HH:mm:ss");
            data.date_to = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var feeType = (string[])queryEventArgs.CustomData;
            data.feeType = feeType[queryEventArgs.Page.Temp1];
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, JF_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                JF_BaseResponseDTO_<JF_FeeItem> result = (JF_BaseResponseDTO_<JF_FeeItem>)JsonConvert.DeserializeObject<JF_BaseResponseDTO_<JF_FeeItem>>(queryEventArgs.ResultStr);
                if (result.msg.IsNullOrEmpty())
                {
                    queryEventArgs.Success = true;
                    if (result.data.Count < queryEventArgs.Page.PageSize)
                    {

                        //判断是否所有的费用类型都循环完成
                        if (queryEventArgs.Page.Temp1 + 1 == queryEventArgs.Page.Temp2)
                        {
                            //查询完成
                            queryEventArgs.Page.PageIndex = 1;
                            queryEventArgs.Page.Complete = true;
                        }
                        else
                        {
                            //查询完成
                            queryEventArgs.Page.PageIndex = 1;
                            queryEventArgs.Page.Temp1 += 1;
                        }

                        if (result.data.Count > 0) queryEventArgs.Rows = result.data;
                    }
                    else
                    {
                        //查询下一页
                        queryEventArgs.Page.PageIndex += 1;
                        queryEventArgs.Rows = result.data;
                    }
                }
                else
                {
                    queryEventArgs.Success = false;
                    AddLog(SqlDb, result.msg, InterfaceName, "erro", "");
                }

            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<JF_FeeItem> invList = await this.QueryAsync<JF_FeeItem>(this.JF_Query, SqlDb);



        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }

    }

}
